import { WereWolfNextTool } from "@/werewolf/components/nextTool";
import { WereWolfPlayerTeleport } from "@/werewolf/components/playerteleporter";
import { WereWolfModule } from "@/werewolf/module";
import { GameMode, world } from "@minecraft/server";
import { RandomUtils } from "@sapi-game/utils";
import { WereWolfRolePattern } from "../static";

export class WereWolfFirstDayPhase extends WereWolfModule.State {
    override onEnter(): void {
        this.addComponent(WereWolfPlayerTeleport);
        //监听下一步
        this.addComponent(WereWolfNextTool, {
            onUse: () => this.popState(),
            getPlayers: () => this.context.players.getAll(),
        });
        //全部传到起始点
        const teleporter = this.getComponent(WereWolfPlayerTeleport);
        teleporter.tpAllToSpeakingLoc();
        world.gameRules.pvp = false;
        this.init();
        //添加地图的view
        this.addComponents(this.context.map.phaseViews.firstDay);
    }

    init() {
        this.context.day = 1;
        this.context.players.forEach((p) => {
            p.clear();
            p.player.setGameMode(
                this.context.config.restrictMode
                    ? GameMode.Adventure
                    : GameMode.Survival
            );
        });
    }

    /**清空身份 */
    reset() {
        this.context.players.getAll().forEach((p) => (p.role = undefined));
    }

    /**分配身份 */
    assign() {
        const players = this.context.players.getAll().filter((p) => p.isValid);

        const count = Math.min(players.length, WereWolfRolePattern.length);
        // 取前 count 个身份
        const assignedRoles = WereWolfRolePattern.slice(0, count);
        //随机打乱
        RandomUtils.shuffleInPlace(assignedRoles);

        for (let i = 0; i < count; i++) {
            players[i].role = assignedRoles[i];
        }
    }

    /**给下一步物品 */
    giveNextItem() {
        this.getComponent(WereWolfNextTool).giveNextItemToReferee();
    }
}
